//
//  NoticeViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/9/14.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "HistoryViewController.h"
#import "NoticeTableViewCell.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshBackNormalFooter.h"
#import "UIColor+Hex.h"
#import "AFHTTPRequestOperationManager.h"
#import "MBProgressHUD+MJ.h"
#import "HttpReauestParam.h"
#import "UserDefaultUtil.h"
#import "NoticeDetailViewController.h"
#import "WalletLogTableViewCell.h"

#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试
@interface HistoryViewController ()
@property NSMutableArray *noticeData;
@property NSArray *dataArray;
@property NSString *myear;
@property NSString *monthDay;

@property int size;
@property int page;
@property NSString *startDate;
@property NSString *endDate;
@property NSString *type;

@end

@implementation HistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _type = @"0";
    _date_bg.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    [_sx_btn setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [_sx_btn addTarget:self action:@selector(showSXView) forControlEvents:UIControlEventTouchUpInside];
    NSDateFormatter *sf = [[NSDateFormatter alloc]init];
    
    [sf setDateFormat:@"yyyy年MM月"];
    
    _date_lab.text = [sf stringFromDate:[NSDate date]];
    
    _size = 20;
    _page = 1;
    //tabView初始化
    self.table_view.delegate = self;
    self.table_view.dataSource = self;
    
    UINib *nib = [UINib nibWithNibName:@"WalletLogTableViewCell" bundle:nil];
    [self.table_view registerNib:nib forCellReuseIdentifier:@"wallet_cell"];
    
    
    if ([self.table_view respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.table_view setSeparatorInset:UIEdgeInsetsZero];
    }
    self.table_view.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    __unsafe_unretained UITableView *tableView = self.table_view;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新数据");
        
        _page = 1;
        [self getData:_type];
        [tableView.mj_header endRefreshing];
        
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableView.mj_header.automaticallyChangeAlpha = YES;
    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self getData:_type];
        [tableView.mj_footer endRefreshing];
        
    }];
    [tableView.mj_header beginRefreshing];
    //初始化时间选择框
    [self initPickView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WalletLogTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"wallet_cell"];
    
    NSDictionary *dic = _noticeData[indexPath.row];
    
    
    cell.bankImage = [cell viewWithTag:1];
    cell.lab_content = [cell viewWithTag:11];
    cell.lab_date = [cell viewWithTag:111];
    cell.lab_amount = [cell viewWithTag:1111];
    
    cell.lab_date.text = dic[@"created_date"];
    
    if ([dic[@"type"] integerValue] == 2) {
        //支出
        cell.lab_amount.text = [NSString stringWithFormat:@"-%@",dic[@"amount"]];
        //系统
        if ([dic[@"card_type"] integerValue] == 0) {
            
            cell.bankImage.image = [UIImage imageNamed:@"wallet_system"];
            cell.lab_content.text = [NSString stringWithFormat:@"提现-%@",dic[@"cost_msg"]];
        }
        //卡
        if ([dic[@"card_type"] integerValue] == 1) {
            
            cell.bankImage.image = [UIImage imageNamed:@"wallet_bank"];
            cell.lab_content.text = [NSString stringWithFormat:@"提现-***%@",dic[@"cost_msg"]];
        }
        //支付宝
        if ([dic[@"card_type"] integerValue] == 2) {
            
            cell.bankImage.image = [UIImage imageNamed:@"wallet_zfb"];
            cell.lab_content.text = [NSString stringWithFormat:@"提现-%@",dic[@"cost_msg"]];
        }
    }else{
        //收入
        cell.lab_amount.text = [NSString stringWithFormat:@"+%@",dic[@"amount"]];
        
        //系统
        if ([dic[@"card_type"] integerValue] == 0) {
            
            cell.bankImage.image = [UIImage imageNamed:@"wallet_system"];
            cell.lab_content.text = [NSString stringWithFormat:@"充值-%@",dic[@"income_msg"]];
        }
        //卡
        if ([dic[@"card_type"] integerValue] == 1) {
            
            cell.bankImage.image = [UIImage imageNamed:@"wallet_bank"];
            cell.lab_content.text = [NSString stringWithFormat:@"充值-***%@",dic[@"income_msg"]];
        }
        //支付宝
        if ([dic[@"card_type"] integerValue] == 2) {
            
            cell.bankImage.image = [UIImage imageNamed:@"wallet_zfb"];
            cell.lab_content.text = [NSString stringWithFormat:@"充值-%@",dic[@"income_msg"]];
        }
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 68;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return _noticeData.count;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)initPickView{
    //初始化数据
    [self initData];
    
    UIView *dialogView = [[UIView alloc]initWithFrame: CGRectMake(0, ScreenHeight, ScreenWidth, 260)];
    dialogView.backgroundColor = [UIColor colorWithHexString:@"f2f2f2"];
    dialogView.tag = 111111;
    dialogView.hidden = YES;
    
    UIButton * cancle = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 60, 30)];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    cancle.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [cancle setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [cancle addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * ok = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - 70, 10, 60, 30)];
    ok.tag = 55;
    ok.titleLabel.font = [UIFont systemFontOfSize:13 ];
    [ok setTitle:@"确定" forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#ff7e00"] forState:UIControlStateNormal];
    [ok setTitleColor:[UIColor colorWithHexString:@"#55ff7e00"] forState:UIControlStateSelected];
    [ok addTarget:self action:@selector(dialogBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    UIPickerView *pickView1 = [[UIPickerView alloc]initWithFrame:CGRectMake(10, 40,(ScreenWidth - 20) , 200)];
    //pickView1.backgroundColor = [UIColor greenColor];
    
    
    
    
    
    pickView1.showsSelectionIndicator = YES;
    
    
    
    [dialogView addSubview:cancle];
    [dialogView addSubview:ok];
    [dialogView addSubview:pickView1];
    
    [self.view addSubview:dialogView];
    
    pickView1.dataSource = self;
    pickView1.delegate = self;
    
    
    NSDate * date = [NSDate date];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    comps = [calendar components:unitFlags fromDate:date];
    
    int year = [comps year];
    int month = [comps month];
    
    _startDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year,month];
    _endDate = [NSString stringWithFormat:@"%i-%i-01 00:00:00",year,month + 1];
    
    [pickView1 selectRow:0 inComponent:0 animated:NO];
    [pickView1 selectRow:month - 1 inComponent:1 animated:NO];
    [self pickerView:pickView1 didSelectRow:0 inComponent:0];
    [self pickerView:pickView1 didSelectRow:month - 1 inComponent:1];
    
}

-(void)dialogBtn:(UIButton *) button{
    [self showTimeView:button];
    if (button.tag == 55) {
        //  self.oppointBtn.titleLabel.text = [NSString stringWithFormat:@"%@年%@%@",self.myear,self.monthDay,self.mTime];
        
        _startDate = [NSString stringWithFormat:@"%@-%@-01 00:00:00",_myear,_monthDay];
        if ([_monthDay integerValue]+ 1 == 13) {
            _endDate = [NSString stringWithFormat:@"%li-%@-01 00:00:00",[_myear integerValue] + 1,@"01"];
        }else{
            _endDate = [NSString stringWithFormat:@"%@-%li-01 00:00:00",_myear,[_monthDay integerValue]+ 1];
        }
        
        _date_lab.text = [NSString stringWithFormat:@"%@年%@月",_myear,_monthDay];
        _page = 1;
        [self getData:_type];
    }
}

-(NSInteger)initData{
    
    NSInteger result = 0;
    NSDate * date = [NSDate date];
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSCalendarUnitMonth | NSCalendarUnitDay;
    
    comps = [calendar components:unitFlags fromDate:date];
    
    int year = [comps year];
    
    int month = [comps month];
    
    
    
    
    NSArray * array1 = @[[NSString stringWithFormat:@"%i",year],[NSString stringWithFormat:@"%i",year + 1]];
    
    NSMutableArray *monthDay = [[NSMutableArray alloc]init];
    for (int i = 1; i <= 12; i++) {
        
        [monthDay addObject:[NSString stringWithFormat:@"%i",i]];
    }
    
    
    self.dataArray = @[array1,monthDay];
    
    return result;
}


-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    NSLog(@"numberOfComponentsInPickerView");
    return self.dataArray.count;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSLog(@"numberOfRowsInComponent");
    NSArray * array = [self.dataArray objectAtIndex:component];
    
    return array.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSArray * array = [self.dataArray objectAtIndex:component];
    
    NSString *s = [array objectAtIndex:row];
    
    return s;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"%@",self.dataArray[component][row]);
    
    if (component == 0) {
        self.myear = self.dataArray[component][row];
    }
    if (component == 1) {
        self.monthDay = self.dataArray[component][row];
    }
}



- (IBAction)showTimeView:(id)sender {
    UIView *timeView = [self.view viewWithTag:111111];
    if (timeView.hidden) {
        timeView.hidden = NO;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight - 260, ScreenWidth, 260);
        }];
        
    }else{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            // 设置view弹出来的位置
            
            timeView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 260);
            timeView.hidden = YES;
        }];
        
        
    }
}

- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) getData:(NSString *)type{
    
    NSString *userId =[UserDefaultUtil getUserId];
    NSDictionary * dic = @{@"identifier": userId ,@"page":[NSString stringWithFormat:@"%i",_page],@"size":[NSString stringWithFormat:@"%i",_size],@"startDate":_startDate,@"endDate":_endDate,@"type":type};
    
    NSLog(@"%@",dic);
    
    HttpReauestParam * param = [[HttpReauestParam alloc]initWithData:@"profit_record" content:[self dictionaryToJson:dic] urlType:0];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    // [MBProgressHUD showMessage:@"获取订单"];
    [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
        
        
        if ([data[@"success"] boolValue]) {
            _page++;
            NSArray *orderd = data[@"result"];
            
            NSLog(@"%@",orderd);
            
            
            if (_page == 2) {
                self.noticeData = [[NSMutableArray alloc]init];
                [self.noticeData addObjectsFromArray:orderd];
            }else{
                [self.noticeData addObjectsFromArray:orderd];
            }
            
            
            [self.table_view reloadData];
            
        }else{
            [MBProgressHUD showError:data[@"errorMsg"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:@"网络连接失败"];
    }];
}


-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

-(void)showSXView{
    UIControl *view = [self.view viewWithTag:12321];
    if (view != nil) {
        if (view.hidden) {
            view.hidden = NO;
        }else{
            view.hidden = YES;
        }
    }else{
        view = [[UIControl alloc]initWithFrame:CGRectMake(_date_bg.frame.origin.x, _date_bg.frame.origin.y, ScreenWidth, ScreenHeight)];
        view.tag = 12321;
        UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 120)];
        contentView.backgroundColor = [UIColor whiteColor];
        [view addTarget:self action:@selector(closeSXView:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:contentView];
        
        
        int widght = ScreenWidth / 3 - 40;
        
        UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(20, 15, widght, 35)];
        [btn1 setTitle:@"全部" forState:UIControlStateNormal];
        [btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn1.layer setBorderWidth:1];
        [btn1.layer setBorderColor:[UIColor colorWithHexString:@"#cccccc"].CGColor];
        btn1.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn1 setBackgroundImage:[self createImageWithColor:[UIColor grayColor]] forState:UIControlStateSelected];
        [contentView addSubview:btn1];
        
        UIButton *btn2 = [[UIButton alloc]initWithFrame:CGRectMake(60 + widght, 15,widght, 35)];
        [btn2 setTitle:@"收入" forState:UIControlStateNormal];
        [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn2.layer setBorderWidth:1];
        [btn2.layer setBorderColor:[UIColor colorWithHexString:@"#cccccc"].CGColor];
        btn2.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn2 setBackgroundImage:[self createImageWithColor:[UIColor grayColor]] forState:UIControlStateSelected];

        [contentView addSubview:btn2];
        
        UIButton *btn3 = [[UIButton alloc]initWithFrame:CGRectMake(100 + 2 * widght, 15, widght, 35)];
        [btn3 setTitle:@"支出" forState:UIControlStateNormal];
        [btn3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn3.layer setBorderWidth:1];
        [btn3.layer setBorderColor:[UIColor colorWithHexString:@"#cccccc"].CGColor];
        btn3.titleLabel.font = [UIFont systemFontOfSize:13];

        [btn3 setBackgroundImage:[self createImageWithColor:[UIColor grayColor]] forState:UIControlStateSelected];

        [contentView addSubview:btn3];
        btn1.tag = 1;
        btn2.tag = 2;
        btn3.tag = 3;
        
        [btn1 addTarget:self action:@selector(clickSXView:) forControlEvents:UIControlEventTouchUpInside];
        [btn2 addTarget:self action:@selector(clickSXView:) forControlEvents:UIControlEventTouchUpInside];
        [btn3 addTarget:self action:@selector(clickSXView:) forControlEvents:UIControlEventTouchUpInside];
        
        view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        
        [self.view addSubview:view];
    }
}

-(void)closeSXView:(UIControl *) view{
    
    view.hidden = YES;
}
-(void)clickSXView:(UIButton *) btn{
    
    
    
    switch (btn.tag) {
        case 1:
            _type = @"0";
            break;
        case 2:
            _type = @"1";
            break;
        case 3:
            _type = @"2";
            break;
        default:
            break;
    }
    _page = 1;
    [self getData:_type];
    UIView *view = [self.view viewWithTag:12321];
    view.hidden = YES;
}

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}
@end
